<template>
  <el-form label-position="left" :model="user" ref="form" :rules="rules" size="mini">

    <el-form-item label="用户名" prop="username">
      <el-input v-model="user.username" type="text" @blur="show"></el-input>
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input v-model="user.password" type="password"></el-input>
    </el-form-item>

    <el-form-item label="再次确认密码密码" prop="password2">
      <el-input v-model="user.password2" type="password"></el-input>
    </el-form-item>

    <el-form-item label="请输入验证码" v-show="user.isshow">
      <el-input v-model="user.imagecode"></el-input>
      <img :src="imges" alt="验证图片加载失败" width="100" @click="getimges">
    </el-form-item>

    <el-form-item>
      <el-button @click="reg" type="primary">注册</el-button>
    </el-form-item>

  </el-form>
</template>

<script>
  export default {
    name: "Register",
    data: function () {
      var PWD = (rule, value, callback) => {
        if (value !== this.user.password) {
          callback(new Error('两次输入密码不一致!'));
        }
      };
      return {
        imges: '',
        user: {
          'username': '',
          'password': '',
          'password2': '',
          'isshow': false,
          'imagecode': ''
        },
        rules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'}
          ],
          password2: [
            {validator: PWD, trigger: 'blur'}
          ]
        }
      }

    },
    methods: {
      reg() {
        console.log(this.user);
        this.axios({
          url: "http://127.0.0.1:8000/myapp/reg/",
          method: "post",
          data: {"username": this.user.username, "password": this.user.password, 'imagecode': this.user.imagecode}
        }).then(res => {
          if (res.data.code == 200) {
            alert(res.data.data);
          } else {
            alert(res.data.data);
          }
        })
      },
      show() {
        console.log('弹出验证码框');
        this.user.isshow = true;
        this.imges = 'http://127.0.0.1:8000/myapp/img/?username= ' + this.user.username
      },
      getimges() {
        var code = Math.random();
        this.imges = 'http://127.0.0.1:8000/myapp/img/?username=' + this.user.username + '&' + code;
      }
    }
  }
</script>

<style scoped>

</style>
